package service;

import java.util.HashMap;
import java.util.Map;

import light.im.IMSession;
import light.im.loginserver.domain.model.Client;
import light.im.loginserver.domain.user.UserService;
import light.im.loginserver.domain.user.model.User;

public class LoginService {

	Map<String, Client> userStore = new HashMap<String, Client>();
	
	private static LoginService instance = new LoginService();
	{
		Client c = new Client();
		c.setSessionId("123456");
		c.setUserId("pig");
		c.setPort(30001);
		userStore.put("pig", c);
		c = new Client();
		c.setSessionId("xxyy");
		c.setUserId("ruby");
		c.setPort(30002);
		userStore.put("ruby", c);
	}
	
	private LoginService(){}
	public static LoginService getInstance(){
		return instance;
	}
	
	public boolean login(IMSession session, String userId, String psw)
	{
		User user = UserService.validate(userId, psw);
		if(user==null)
		{
			return false;
		}
		else
		{
			setupClient(session, userId);
			return true;
		}
	}
	public Client isLogin(String userId)
	{
		return userStore.get(userId);
	}
	
	private void setupClient(IMSession session, String userId)//
	{
		Client client = new Client();
		client.setUserId(userId);
		client.setSessionId(genSessionId(session, userId));
		userStore.put(userId, client);
	}
	
	public Client getClient(String userId)
	{
		return userStore.get(userId);
	}
	
	/**
	 * 创建客户端会话标识
	 * @return
	 */
	private static String genSessionId(IMSession session, String userName)
	{
		//return UUID.randomUUID().toString();
		return String.valueOf(session.getId());
	}
}
